<template>
  <el-dialog title="导入Id和订单数组文件" :visible.sync="open" width="40%" append-to-body :before-close="cancel">
    <el-form ref="form" :model="form" :rules="rules" label-width="100px">
    <el-form-item label="文件">
      <el-upload
        class="upload-demo"
        :action="uploadUrl"
        :on-change="handleChange"
        :before-upload="handelCheckFile"
        :file-list="fileList"
        accept=".xls, .xlsx"
        :headers="headers"
        :auto-upload="true"
        :on-success="fileSuccessUpload"
        drag
        >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <el-button size="small" type="primary">点击上传</el-button>
        <div slot="tip" class="el-upload__tip">只能上传.xls/.xlsx文件，且不超过5MB</div>
      </el-upload>
    </el-form-item>
    </el-form>
    <div slot="footer" class="flex-center">
      <el-button type="primary" @click="submitForm" :loading="buttonLoading">解析数据</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { getToken } from '@/utils/auth'
import { importJinFenData } from '@/api/mx/rebate'

export default {
  name: 'importOrders',
  props:{
    //父页面的打开条件
    open:{
      default:false
    },
  },
  data(){
    return{
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      fileList:[],
      uploadUrl: process.env.VUE_APP_BASE_API + "/jd/rebate/order/importIdAndOrderExcel",
      accept:  ".xls, .xlsx",
      // 表单参数
      form: {
      },
      fileSize: '5M',
      // 表单校验
      rules: {
       /*  sealId: [
          { required: true, message: "电子印章ID不能为空", trigger: "blur" }
        ],
        branchNo: [
          { required: true, message: "请填写开户代办点", trigger: "blur" }
        ],
        physicalSealId: [
          { required: true, message: "请选择实体印章", trigger: "blur" }
        ],
        currentUser: [
          { required: true, message: "请选择监交人", trigger: "blur" }
        ], */

      },
      buttonLoading: false
    }
  },
  methods:{
    /********************************* 文件传下载 *********************************/
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePreview(file) {
      this.fileList.push(file.raw);
      console.log(file);
    },
    handleChange(file, fileList){
      this.fileList=fileList;
    },

    downloadFile(row){
      let data={
        url:row.url
      }
      this.download('elecSeal/downloadFile', {
        ...data
      }, row.name)

    },
    //文件检测
    handelCheckFile(file){
      const FileExt = file.name.replace(/.+\./, '')
      if(this.accept.toLowerCase().indexOf(FileExt.toLowerCase()) === -1){
        this.$message.error('请上传后缀名为' + this.accept + '的文件！')
        return false
      }
      /* // 文件名校验
       const reg = this.fileNameRule.rule
       const name = file.name.split('.')
       if(reg.test(name)){
         this.$message.warning(this.fileNameRule.error)
         return false
       }*/
      // 文件大小
      let numberStr = ''
      let unitStr = ''
      this.fileSize.split('').forEach(item => {
        if(!isNaN(Number(item))){
          numberStr = numberStr + item + ''
        }else{
          unitStr = unitStr + item
          unitStr = unitStr.toLowerCase()
        }
      })
      let totalSize = file.size
      let errMessage = ''
      switch(unitStr){
        case 'm': case 'mb':
          totalSize = file.size / 1024 / 1024
          break
        case 'k': case 'kb':
          totalSize = file.size / 1024
          break
        case 'g': case 'bg':
          errMessage = '暂不接受gb级别的文件上传！'
          break
      }
      const isOverSize = totalSize > Number(numberStr)
      const sizeZero = totalSize === 0
      if(errMessage){
        this.$message.warning(errMessage)
        return false
      }else if(isOverSize){
        this.$message.warning('文件大小超过' + this.fileSize + '！')
        return false
      }else if(sizeZero){
        this.$message.warning('文件无内容！')
        return false
      }
      // 添加文件
      // this.fileList.push(file)
      //this.$emit('store-local', file)
    },
    success(res,file,fileList) {
      if (res.code === 200) {
        this.$message.success('上传成功');
        this.fileName = res.data.name;
        console.log(this.fileName,"文件名");
        this.$emit('sendFile', res.data)
      } else if (res.code===500) {
        this.$message.error('文件上传失败');
        let index = 0;
        //移出当前文件对象
        fileList.splice(this.fileList.length-1,1);
      }


    },
    fileSuccessUpload(response, file, fileList){
      console.log(file)
      this.fileList=fileList;
    },
    beforeRemove(file, fileList) {


    },
    //关闭
    cancel() {
      this.buttonLoading = false
      this.fileList = []
      this.form = null
      console.log("关闭")
      this.$emit('close')
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.buttonLoading = true;
            let obj = {}

            let formData = new FormData();
            //附件
            if (this.fileList.length > 0) {
              let newFileList = {};
              this.form.fileList = [];
              this.fileList.forEach(file => {
                formData.append("fileList", file.raw);
                //this.form.fileList.push(file.raw);
              });
            }
            formData.append("form", JSON.stringify(this.form));
            //获得营业部编号
          importJinFenData(formData).then(res => {
              if (res.code === 200) {
                this.cancel()
                this.$message.success("上传成功");
              }

            }).catch(()=> this.buttonLoading = false).finally(()=> this.buttonLoading = false);
        }
      });
    },
  }
}
</script>

<style scoped>

</style>
